﻿using Autodesk.Revit.UI;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using Microsoft.WindowsAPICodePack.Shell;
using System.Drawing;
using System.Drawing.Imaging;

namespace spark
{
    /// <summary>
    /// UserControl1.xaml 的交互逻辑
    /// </summary>
    public partial class SparkWindow : Window
    {
        private string currentProjectId;
        private string currentProjectName;
        private EventFunction eventFunction = null;
        private ExternalEvent externalEvent = null;
        private string workPath;
        private string currentFilename = null;
        private string currentFileUrl = null;
        private string currentETag = null;
        
        public SparkWindow()
        {
            InitializeComponent();
            eventFunction = new EventFunction();
            externalEvent = ExternalEvent.Create(eventFunction);
            LoadBtn.IsEnabled = false;
            TreeList.Visibility = Visibility.Hidden;
            ComponentView.Visibility = Visibility.Hidden;
            BtnComDownload.IsEnabled = false;
            BtnComRemove.IsEnabled = false;
            BtnComLoad.IsEnabled = false;
            BtnComPreview.IsEnabled = false;
            var fileName = Assembly.GetExecutingAssembly().Location;
            workPath = fileName.Substring(0, fileName.LastIndexOf(@"\"));
        }

        private void ComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        { 
        }

        private void SearchBtn(object sender, RoutedEventArgs e)
        {
            var res = Util.SearchProjects();
            TreeList.Visibility = Visibility.Hidden;
            if (res != null && (int)res.GetValue("code") == 200)
            {
                //MessageBox.Show(res.ToString());
                var data = res.GetValue("data").ToObject<EProject[]>();
                MessageBox.Show(res.GetValue("msg").ToString());
                ProjectList.Visibility = Visibility.Visible;
                CreateProjectList(data);
            }
        }

        private void onSelectProject(object sender, RoutedEventArgs e)
        {
            var radioButton = sender as RadioButton;

            //MessageBox.Show(radioButton.Uid);
            currentProjectId = radioButton.Uid;
            currentProjectName = radioButton.Content.ToString();
            if (null != currentProjectId) LoadBtn.IsEnabled = true;
            else LoadBtn.IsEnabled = false;
            
        }

        private void LoadProject(object sender, RoutedEventArgs e)
        {
            // 优化 -> 树形懒加载数据，展开一级加载子级 [fix]
            if (currentProjectId == null) return;
            var res = Util.getAllComponents(currentProjectId);
            if (res == null || (int)res.GetValue("code") != 200) return;
            var properties = res.Properties();
            JToken data = null;
            foreach (JProperty item in properties)
            {
                if (item.Name == "data")
                { 
                    data = item.Value;
                }
            }
            if (null == data) return;
            LoadBtn.IsEnabled = false;
            ProjectList.Visibility = Visibility.Hidden;
            TreeList.Visibility = Visibility.Visible;
            properties = (data as JObject).Properties();
            var firstItems = new List<TreeItem>();
            // 优化 -> 递归 [fix]
            foreach (JProperty item in properties)
            {
                var newFirstItem = new TreeItem() { Name = item.Name };
                firstItems.Add(newFirstItem);
                if ( item.Value == null) continue;
                var properties2 = (item.Value as JObject).Properties();
                foreach (JProperty item2 in properties2)
                {
                    var newSecondItem = new TreeItem() { Name = item2.Name };
                    newFirstItem.Children.Add(newSecondItem);
                    if (item2.Value == null) continue;
                    var properties3 = (item2.Value as JObject).Properties();
                    foreach (JProperty item3 in properties3)
                    {
                        var newThirdItem = new TreeItem() { Name = item3.Name };
                        newSecondItem.Children.Add(newThirdItem);
                        if (item3.Name.IndexOf(":") != -1)
                        {
                            var component = item3.Value as JObject;
                            newThirdItem.ProjectId = component.GetValue("project_id").ToString();
                            newThirdItem.Code = component.GetValue("code").ToString();
                            newThirdItem.RawName = component.GetValue("name").ToString();
                            newThirdItem.ETag = component.GetValue("etag").ToString();
                        }
                        else
                        {
                            if (item3.Value == null) continue;
                            var properties4 = (item3.Value as JObject).Properties();
                            foreach (JProperty item4 in properties4)
                            {
                                var newForthItem = new TreeItem() { Name = item4.Name };
                                newThirdItem.Children.Add(newForthItem);
                                if (item4.Name.IndexOf(":") != -1)
                                {
                                    var component = item4.Value as JObject;
                                    newForthItem.ProjectId = component.GetValue("project_id").ToString();
                                    newForthItem.Code = component.GetValue("code").ToString();
                                    newForthItem.RawName = component.GetValue("name").ToString();
                                    newThirdItem.ETag = component.GetValue("etag").ToString();
                                }
                            }
                        }
                    }
                }
            }
            TreeList.ItemsSource = firstItems;
        }

        private void TreeList_MouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            // MessageBox.Show(sender.ToString());
        }

        private JObject parseComponentsData(JObject data)
        {
            var properties = data.Properties();
            JToken res = null;
            foreach (JProperty item in properties)
            {
                if (item.Name == "data")
                {
                    res = item.Value;
                }
            }
            return null;
        }

        private void CreateProjectList(EProject[] projects)
        {
            List<ProjectItem> items = new List<ProjectItem>();
            for (int i=0;i<projects.Length;i++)
            {
                items.Add(new ProjectItem() { Name = projects[i].name, ProjectId = projects[i].project_id });
            }
            ProjectList.Height = items.Count * 30;
            ProjectList.ItemsSource = items;
        }

        private void TreeList_SelectedItemChanged(object sender, RoutedPropertyChangedEventArgs<object> e)
        {
            var treeItem = TreeList.SelectedItem as TreeItem;
            if (treeItem != null && treeItem.Code != null)
            {
                //MessageBox.Show(treeItem.Name);
                //MessageBox.Show(treeItem.ProjectId);
                ComponentView.Visibility = Visibility.Visible;
                InputProject.Text = currentProjectName;
                InputComponentName.Text = treeItem.RawName;
                InputComponentCode.Text = treeItem.Code;
                currentFilename = workPath + @"\" + treeItem.RawName + ".rfa";
                currentETag = treeItem.ETag;
                if (!File.Exists(currentFilename))
                {
                    BtnComRemove.IsEnabled = false;
                    BtnComLoad.IsEnabled = false;
                    BtnComDownload.IsEnabled = true;
                    BtnComPreview.IsEnabled = false;
                }
                else
                {
                    BtnComRemove.IsEnabled = true;
                    BtnComLoad.IsEnabled = true;
                    BtnComDownload.IsEnabled = false;
                    BtnComPreview.IsEnabled = true;
                }
            }
        }

        private void DownloadComponent(object sender, RoutedEventArgs e)
        {
            
            var downloadRes = Util.Download(currentProjectId, currentETag, currentFilename);
            if (downloadRes)
            {
                BtnComRemove.IsEnabled = true;
                BtnComLoad.IsEnabled = true;
                BtnComDownload.IsEnabled = false;
                BtnComPreview.IsEnabled = true;
                MessageBox.Show("下载成功！");
            }
            else
            {
                MessageBox.Show("网络错误，下载失败！");
            }
        }

        private void DoPreview(object sender, RoutedEventArgs e)
        {

            MessageBox.Show("暂未开放预览功能！");
            //ShellObject so = ShellFile.FromFilePath(currentFilename);
            //Bitmap bm2 = so.Thumbnail.LargeBitmap;
            //ComponentPreview.Source = ChangeBitMapToImageSource(bm2);
        }

        private void RemoveComponent(object sender, RoutedEventArgs e)
        {
            MessageBox.Show("暂未开放删除功能！");
        }

        private void LoadToProject(object sender, RoutedEventArgs e)
        {
            eventFunction.componentPath = currentFilename;
            externalEvent.Raise();
        }

        /**
         * 重载当前按钮
         */
        private bool DoReloadComponent()
        {
            MessageBox.Show("Reload");
            if (!File.Exists(currentFilename))
            {
                MessageBox.Show("Not Found: " + currentFilename);
                BtnComRemove.IsEnabled = false;
                BtnComLoad.IsEnabled = false;
                BtnComDownload.IsEnabled = true;
                return false;
            }
            else
            {
                BtnComRemove.IsEnabled = true;
                BtnComLoad.IsEnabled = true;
                BtnComDownload.IsEnabled = false;
                //ShellObject so = ShellFile.FromFilePath(currentFilename);
                //Bitmap bm2 = so.Thumbnail.LargeBitmap;
                //ComponentPreview.Source = ChangeBitMapToImageSource(bm2);
                MessageBox.Show("显示构件");
                return true;
            }
        }

        private ImageSource ChangeBitMapToImageSource(Bitmap bitmap)
        {
            MemoryStream stream = new MemoryStream();
            bitmap.Save(stream, ImageFormat.Bmp);
            stream.Position = 0;
            BitmapImage bitmapImage = new BitmapImage();
            bitmapImage.BeginInit();
            bitmapImage.StreamSource = stream;
            bitmapImage.EndInit();
            return bitmapImage;
        }
    }

    public class ProjectItem 
    {
        public string Name { get; set; }
        public string ProjectId { get; set; }
    }
}
